package com.jack;

import com.jack.utils.RMSUtil;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;

public class HomeworkMidlet extends MIDlet implements CommandListener {

    private final String RecordStoreName = "CounterStore";
    final String defaultImagePath = "/images/amtf_image.jpg";
    Display display;
    CounterCanvas canvas;
    CounterItem counterItem;
    // menu and menu commands
    List menu;
    Command openCommand;
    Command exitCommand;
    Command aboutCommand;
    Command helpCommand;
    Command addItemCommand;
    Command deleteItemCommand;
    Command editItemCommand;
    Command settingCommand;
    //test for recordstore
    Command systemCommand;
    SystemForm systemForm;
    String[] defaultMenuIetms = {"阿弥陀佛圣号", "观世音菩萨圣号", "地藏王菩萨圣号", "六字大明咒", "准提咒"};
    
    String nowString = "";
    private static Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
    RecordStore counterRs = null;
    boolean anyKey = false;
    boolean playSound = false;
    boolean showImage = false;
    boolean negativeColor = false;
    boolean showTime = false;
    boolean fullScreen = false;
    Alert errorAlert = new Alert("错误", "", null, AlertType.INFO);
    Alert alert;
    private RecordEnumeration recordEnum;
    //confirm alert command
    Command confirmOkCommand;
    Command confirmCancelCommand;

    public HomeworkMidlet() {
        try {
            log("HomeworkMidlet called.");
            display = Display.getDisplay(this);

            init();
            initRS();
            initMenu();

            canvas = new CounterCanvas(this);

            menu.setSelectedIndex(0, true);

            systemForm = new SystemForm(this);
            systemForm.setRs(counterRs);

        } catch (Exception ex) {
            log("error:" + ex.toString());
            showAlert(ex.toString());
        }
    }

    protected void destroyApp(boolean arg0) {
        saveCounter(counterItem);
        recordEnum.destroy();
        recordEnum = null;
        closeRs();
        log("destroyApp called." + arg0);
    }

    protected void pauseApp() {
        log("pauseApp called.");
    }

    protected void startApp() {
        log("startApp called.");
        display.setCurrent(menu);
    }

    private void init() {

        menu = new List("请选择...", List.IMPLICIT, defaultMenuIetms, null);

        openCommand = new Command("打开", Command.OK, 0);
        exitCommand = new Command("退出", Command.EXIT, 1);

        addItemCommand = new Command("添加", Command.ITEM, 1);
        settingCommand = new Command("修改", Command.ITEM, 2);
        deleteItemCommand = new Command("删除", Command.ITEM, 3);
        systemCommand = new Command("工具", Command.ITEM, 4);
        helpCommand = new Command("帮助", Command.ITEM, 5);
        aboutCommand = new Command("关于", Command.ITEM, 6);

        menu.addCommand(exitCommand);
        menu.addCommand(openCommand);
        menu.addCommand(aboutCommand);
        //menu.addCommand(helpCommand);
        menu.addCommand(settingCommand);
        menu.addCommand(addItemCommand);
        menu.addCommand(deleteItemCommand);
        menu.addCommand(systemCommand);

        menu.setSelectCommand(openCommand);

        menu.setCommandListener(this);
    }

    private void initRS() {
        try {
            counterRs = RecordStore.openRecordStore(RecordStoreName, true);
            if (counterRs.getNumRecords() == 0) {
                for (int i = 0; i < menu.size(); i++) {
                    CounterItem item = new CounterItem(menu.getString(i), 0, i);
                    item.setBackColor(0xffffff);
                    item.setForeColor(0x000000);
                    item.setImagePath(defaultImagePath);
                    item.setAnyKeyCount(false);
                    item.setFullSceenMode(false);
                    item.setKeepScale(true);
                    item.setShowImage(true);
                    byte[] bytes = item.getBytes();
                    counterRs.addRecord(bytes, 0, bytes.length);
                }
            }
        } catch (Exception ex) {
            log(ex);
            showAlert(ex.toString());
        }
    }

    public RecordEnumeration getRecordEnum() throws RecordStoreNotOpenException {
        if (recordEnum == null) {
            recordEnum = RMSUtil.getRecordEnum(counterRs);
        }
        recordEnum.reset();
        return recordEnum;
    }

    // 如果RS里有记录，就用这些记录覆盖menu
    private void initMenu() {
        try {
            if (counterRs.getNumRecords() > 0) {
                menu.deleteAll();
                RecordEnumeration re = getRecordEnum();

                while (re.hasNextElement()) {
                    int recordId = re.nextRecordId();
                    if (recordId == -1) {
                        continue;
                    }
                    byte[] bytes = counterRs.getRecord(recordId);
                    CounterItem item = new CounterItem(bytes);
                    if (item.getName() == null
                            || "".equals(item.getName())
                            || " ".equals(item.getName())) {
                        continue;
                    }
                    if (!menuItemExists(item.getName())) {
                        menu.append(item.getName(), null);
                    } else {
                        //menu item exists.
                    }
                }
            }
        } catch (Exception ex) {
            log(ex);
            showAlert(ex.toString());
        }
    }

    private void removeMenuItem(CounterItem item) {
        try {
            if (item.getName().equals(menu.getString(menu.getSelectedIndex()))) {
                menu.delete(menu.getSelectedIndex());
                log(item.getName() + " deleted from menu.");
                if (item.getRecordId() != -1) {
                    counterRs.deleteRecord(item.getRecordId());
                    log(item.getName() + " deleted from database.");
                    /*
                     * update RecordEnumeration
                     */
                    recordEnum = RMSUtil.getRecordEnum(counterRs);
                    showAlert("deleted.");
                }
            }

        } catch (Exception ex) {
            log(ex);
            //showAlert(ex.toString());
        }
    }

    protected void addMenuItem(CounterItem item) {
        try {
            if (item == null || item.getName() == null || "".equals(item.getName()) || " ".equals(item.getName())) {
                log("Item is empty, can't be saved.");
                return;
            }
            log("Recordid: " + item.getRecordId());
            if (item.getRecordId() > 0) {
                byte[] bytes = item.getBytes();
                counterRs.setRecord(item.getRecordId(), bytes, 0, bytes.length);
            } else {
                // if exists,return.
                if (menuItemExists(item.getName())) {
                    log("Item exists in menu, can't be saved.");
                    return;
                }

                if (recordItemExists(item.getName())) {
                    log("Item exists in record store, can't be saved.");
                    return;
                }

                //check properties
                if (item.getSequence() <= 0) {
                    item.setSequence(menu.size() + 1);
                }

                byte[] bytes = item.getBytes();

                counterRs.addRecord(bytes, 0, bytes.length);
                menu.append(item.getName(), null);
                /*
                 * update RecordEnumeration
                 */
                recordEnum = RMSUtil.getRecordEnum(counterRs);
            }

        } catch (Exception ex) {
            log(ex);
            showAlert(ex.toString());
        }
    }

    private boolean menuItemExists(String value) {
        boolean result = false;
        for (int i = 0; i < menu.size(); i++) {
            if (menu.getString(i).equals(value)) {
                result = true;
                break;
            }
        }
        return result;
    }

    private boolean recordItemExists(String value) {
        boolean result = false;
        try {
            if (value == null || value.equals("")) {
                return false;
            }

            RecordEnumeration re = getRecordEnum();
            while (re.hasNextElement()) {
                int recordId = re.nextRecordId();
                if (recordId == -1) {
                    continue;
                }

                byte[] bytes = counterRs.getRecord(recordId);

                CounterItem item = new CounterItem(bytes);

                if (item.getName().equals(value)) {
                    result = true;
                    break;
                }
            }

        } catch (Exception ex) {
            log(ex);
            showAlert(ex.toString());
        }

        return result;
    }

    private void closeRs() {
        try {
            if (counterRs != null) {
                counterRs.closeRecordStore();
            }
        } catch (Exception ex) {
            showAlert(ex.toString());
        }
    }

    public void makeCurrent() {
        display.setCurrent(menu);
    }
    private static StringBuffer sb = new StringBuffer("");

    public static String getCurrentTime() {
//		StringBuffer sb = new StringBuffer();
        sb = sb.delete(0, sb.length());
        now.setTime(new Date());
        //now.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        sb.append(now.get(Calendar.YEAR)).append("/");

        if ((now.get(Calendar.MONTH) + 1) < 10) {
            sb.append("0").append(now.get(Calendar.MONTH) + 1).append("/");
        } else {
            sb.append(now.get(Calendar.MONTH) + 1).append("/");
        }

        if (now.get(Calendar.DATE) < 10) {
            sb.append("0").append(now.get(Calendar.DATE)).append(" ");
        } else {
            sb.append(now.get(Calendar.DATE)).append(" ");
        }

        if (now.get(Calendar.HOUR_OF_DAY) < 10) {
            sb.append("0").append(now.get(Calendar.HOUR_OF_DAY)).append(":");
        } else {
            sb.append(now.get(Calendar.HOUR_OF_DAY)).append(":");
        }

        if (now.get(Calendar.MINUTE) < 10) {
            sb.append("0").append(now.get(Calendar.MINUTE)).append(":");
        } else {
            sb.append(now.get(Calendar.MINUTE)).append(":");;
        }

        if (now.get(Calendar.SECOND) < 10) {
            sb.append("0").append(now.get(Calendar.SECOND));
        } else {
            sb.append(now.get(Calendar.SECOND));;
        }

        return sb.toString();
    }

    public final void log(String msg) {
        System.out.println(msg);
    }

    public void log(Exception ex) {
        System.out.println(ex.toString());
    }

    private CounterItem getCounterItem(String title) {
        CounterItem result = null;
        try {
            RecordEnumeration re = getRecordEnum();

            while (re.hasNextElement()) {
                int recordId = re.nextRecordId();
                byte[] bytes = counterRs.getRecord(recordId);

                CounterItem item = new CounterItem(bytes);
                item.setRecordId(recordId);

                if (item.getName().equals(title)) {
                    result = item;
                    break;
                }
            }

        } catch (RecordStoreNotOpenException ex) {
            log(ex);
        } catch (InvalidRecordIDException ex) {
            log(ex);
        } catch (RecordStoreException ex) {
            log(ex);
        } catch (IOException ex) {
            log(ex);
        }
        return result;
    }

    void saveCounter(CounterItem item) {
        try {
            if (item.getRecordId() != -1) {
                byte[] data = item.getBytes();
                counterRs.setRecord(item.getRecordId(), data, 0, data.length);
            } else {
                //No RecordId Found.			
            }

        } catch (Exception ex) {
            showAlert(ex.toString());
        }
    }

    private void showAlert(String msg) {
        if (msg == null || "".equals(msg)) {
            errorAlert.setString("String is empty.");
            errorAlert.setTimeout(Alert.FOREVER);
            display.setCurrent(errorAlert, menu);
            return;
        }
        errorAlert.setString(msg);
        errorAlert.setTimeout(Alert.FOREVER);

        display.setCurrent(errorAlert);
    }

    private void showAbout() {
        Alert aboutAlert = new Alert("关于", "这是一个多功能念佛、念咒计数程序。\r\n可以用于平常功课的计数。", null,
                AlertType.INFO);
        aboutAlert.setTimeout(Alert.FOREVER);
        display.setCurrent(aboutAlert);
    }

    private void showHelp() {
        Alert helpAlert = new Alert("帮助", "按任意键增加计数。", null,
                AlertType.INFO);
        helpAlert.setTimeout(Alert.FOREVER);
        display.setCurrent(helpAlert);
    }

    public Alert getConfirmAlert(String text) {
        if (alert == null) {
            alert = new Alert("alert", "<null>", null, null);
            alert.setTitle("删除确认");
            alert.setString(text);
            confirmCancelCommand = new Command("取消", Command.SCREEN, 0);
            confirmOkCommand = new Command("确认", Command.SCREEN, 1);
            alert.addCommand(confirmCancelCommand);
            alert.addCommand(confirmOkCommand);
            alert.setCommandListener(this);
            alert.setTimeout(Alert.FOREVER);
        }
        return alert;
    }

    public void commandAction(Command c, Displayable d) {
        try {
            if (d == menu) {
                if (c == openCommand || c == List.SELECT_COMMAND) {
                    counterItem = getCounterItem(menu.getString(menu.getSelectedIndex()));
                    canvas.setCounterItem(counterItem);
                    display.setCurrent(canvas);
                } else if (c == addItemCommand) {
                    EditForm editForm = new EditForm(this);
                    editForm.setTitle("添加");
                    display.setCurrent(editForm);
                } else if (c == deleteItemCommand) {
                    counterItem = getCounterItem(menu.getString(menu.getSelectedIndex()));
                    String text = "你确认要删除\"" + menu.getString(menu.getSelectedIndex()) + "\"吗？";
                    display.setCurrent(getConfirmAlert(text));
                } else if (c == exitCommand) {
                    saveCounter(counterItem);
                    closeRs();
                    destroyApp(true);
                    notifyDestroyed();
                } else if (c == settingCommand) {
                    log("selected: " + menu.getSelectedIndex());
                    if (menu.getSelectedIndex() == -1) {
                        menu.setSelectedIndex(0, true);
                    }
                    if (counterItem == null) {
                        counterItem = getCounterItem(menu.getString(menu.getSelectedIndex()));
                    }
                    if (!menu.getString(menu.getSelectedIndex()).equals(counterItem.getName())) {
                        counterItem = getCounterItem(menu.getString(menu.getSelectedIndex()));
                    }
                    EditForm editForm = new EditForm(this);
                    editForm.setItem(counterItem);
                    editForm.setTitle("修改 - " + counterItem.getName());
                    display.setCurrent(editForm);

                } else if (c == aboutCommand) {
                    showAbout();
                } else if (c == helpCommand) {
                    showHelp();
                } else if (c == systemCommand) {
                    systemForm.deleteAll();
                    display.setCurrent(systemForm);
                }
            } else if (d == alert) {
                if (c == confirmOkCommand) {
                    log("ok");
                    removeMenuItem(counterItem);
                    display.setCurrent(menu);
                } else if (c == confirmCancelCommand) {
                    log("cancel");
                    display.setCurrent(menu);
                }

            }
        } catch (Exception ex) {
            log(ex);
            showAlert(ex.toString());
        }
    }
}
